﻿#region Using

using System.Collections.Generic;
using System.Linq;

using GameLogic.External;

#endregion

namespace GameLogic.Internal
{

    #region Using

    #endregion

    internal class Route : GameEntity, IRoute
    {
        private readonly Dictionary<Unit, ProgressTimer> unitProgressList;

        internal Route(Tile startTile, Tile endTile)
        {
            this.StartTile = startTile;
            this.EndTile = endTile;
            this.unitProgressList = new Dictionary<Unit, ProgressTimer>();
            this.Enabled = true;
        }

        internal bool Enabled { get; private set; }

        internal Tile EndTile { get; private set; }

        internal Tile StartTile { get; private set; }

        ITile IRoute.EndTile
        {
            get
            {
                return this.EndTile;
            }
        }

        ITile IRoute.StartTile
        {
            get
            {
                return this.StartTile;
            }
        }

        public IEnumerable<KeyValuePair<IUnit, float>> UnitProgressList
        {
            get
            {
                return this.unitProgressList.Select(keyValuePair => new KeyValuePair<IUnit, float>(keyValuePair.Key, keyValuePair.Value.Progress));
            }
        }

        internal void Update(GameTime elapsedTime)
        {
            foreach (var pair in this.unitProgressList.ToList())
            {
                var timer = pair.Value;

                if (timer.Enabled)
                {
                    timer.Update(elapsedTime);
                }
            }
        }

        internal void Receive(Unit unit)
        {
            var timer = new ProgressTimer();

            timer.Elapsed += this.OnProgressTimerElapsed;

            timer.Start(this.Settings.WalkingTimeUnit);

            this.unitProgressList.Add(unit, timer);
        }

        private void OnProgressTimerElapsed(ProgressTimer source)
        {
            var pair = this.unitProgressList.First(x => x.Value == source);

            pair.Key.ArriveAt(this.EndTile);

            this.unitProgressList.Remove(pair.Key);
        }
    }
}